package com.company.ems.controller;

import com.company.ems.dto.PageDTO;
import com.company.ems.mapper.EmployeeMapper;
import com.company.ems.model.Employee;
import com.company.ems.model.User;
import com.company.ems.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
    private static final Integer PAGE_SIZE = 5; // 每页默认5条
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) action = "list";

        // 按操作类型分发
        switch (action) {
            case "list":
                handleList(request, response); // 员工列表（分页）
                break;
            case "add":
                handleAddPage(request, response); // 跳转新增页
                break;
            case "edit":
                handleEditPage(request, response); // 跳转编辑页
                break;
            case "view":
                handleView(request, response); // 查看详情
                break;
            case "delete":
                handleDelete(request, response); // 删除员工
                break;
            default:
                handleList(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if (action == null) action = "";

        switch (action) {
            case "add":
                handleAddSubmit(request, response); // 提交新增
                break;
            case "edit":
                handleEditSubmit(request, response); // 提交编辑
                break;
            default:
                handleList(request, response);
        }
    }

    // ------------------------------ 私有处理方法 ------------------------------
    /**
     * 员工列表（分页）
     */
    private void handleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 处理分页参数
        Integer currentPage = 1;
        String currentPageStr = request.getParameter("currentPage");
        if (currentPageStr != null && !currentPageStr.isEmpty()) {
            try {
                currentPage = Integer.parseInt(currentPageStr);
            } catch (NumberFormatException e) {
                currentPage = 1;
            }
        }
        if (currentPage < 1) currentPage = 1;

        // 2. 分页查询
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            int totalCount = employeeMapper.selectTotalCount();
            int startIndex = (currentPage - 1) * PAGE_SIZE;
            List<Employee> employeeList = employeeMapper.selectPage(startIndex, PAGE_SIZE);

            // 3. 构建分页DTO
            PageDTO<Employee> pageDTO = new PageDTO<>(employeeList, currentPage, PAGE_SIZE, totalCount);

            // 4. 查询部门列表（下拉框用）
            List<String> departments = employeeMapper.selectAllDepartments();

            // 5. 传递数据到页面
            request.setAttribute("pageDTO", pageDTO);
            request.setAttribute("departments", departments);
            request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "查询员工列表失败：" + e.getMessage());
            request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
        }
    }

    /**
     * 跳转新增页
     */
    private void handleAddPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询部门列表（下拉框）
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            List<String> departments = employeeMapper.selectAllDepartments();
            request.setAttribute("departments", departments);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "加载部门失败：" + e.getMessage());
        }
        request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
    }

    /**
     * 提交新增员工
     */
    private void handleAddSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        // 1. 封装员工数据
        Employee employee = new Employee();
        try {
            employee.setName(request.getParameter("name").trim());
            employee.setDepartment(request.getParameter("department").trim());
            employee.setPosition(request.getParameter("position").trim());
            employee.setSalary(new BigDecimal(request.getParameter("salary").trim()));
            employee.setEmail(request.getParameter("email") != null ? request.getParameter("email").trim() : "");
            employee.setPhone(request.getParameter("phone") != null ? request.getParameter("phone").trim() : "");
            employee.setHireDate(DATE_FORMAT.parse(request.getParameter("hireDate").trim()));
            employee.setCreatedBy(loginUser.getId()); // 设置创建人ID

            // 2. 非空校验
            if (employee.getName().isEmpty() || employee.getDepartment().isEmpty() ||
                    employee.getPosition().isEmpty() || employee.getSalary() == null) {
                throw new RuntimeException("姓名、部门、职位、薪资不能为空！");
            }
        } catch (ParseException e) {
            request.setAttribute("errorMsg", "日期格式错误（正确：yyyy-MM-dd）");
            handleAddPage(request, response);
            return;
        } catch (Exception e) {
            request.setAttribute("errorMsg", e.getMessage());
            handleAddPage(request, response);
            return;
        }

        // 3. 新增员工
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            int rows = employeeMapper.insert(employee);
            if (rows > 0) {
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            } else {
                request.setAttribute("errorMsg", "新增失败");
                handleAddPage(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "新增异常：" + e.getMessage());
            handleAddPage(request, response);
        }
    }

    /**
     * 跳转编辑页
     */
    private void handleEditPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取员工ID
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("errorMsg", "员工ID不能为空");
            response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            return;
        }
        Integer id = Integer.parseInt(idStr);

        // 2. 查询员工详情
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.selectById(id);
            if (employee == null) {
                request.setAttribute("errorMsg", "员工不存在");
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
                return;
            }

            // 3. 查询部门和职位列表
            List<String> departments = employeeMapper.selectAllDepartments();
            List<String> positions = employeeMapper.selectPositionsByDepartment(employee.getDepartment());

            // 4. 传递数据
            request.setAttribute("employee", employee);
            request.setAttribute("departments", departments);
            request.setAttribute("positions", positions);
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "加载编辑页失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
        }
    }

    /**
     * 提交编辑员工
     */
    private void handleEditSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取员工ID
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("errorMsg", "员工ID不能为空");
            response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            return;
        }
        Integer id = Integer.parseInt(idStr);

        // 2. 封装员工数据
        Employee employee = new Employee();
        try {
            employee.setId(id);
            employee.setName(request.getParameter("name").trim());
            employee.setDepartment(request.getParameter("department").trim());
            employee.setPosition(request.getParameter("position").trim());
            employee.setSalary(new BigDecimal(request.getParameter("salary").trim()));
            employee.setEmail(request.getParameter("email") != null ? request.getParameter("email").trim() : "");
            employee.setPhone(request.getParameter("phone") != null ? request.getParameter("phone").trim() : "");
            employee.setHireDate(DATE_FORMAT.parse(request.getParameter("hireDate").trim()));

            // 3. 非空校验
            if (employee.getName().isEmpty() || employee.getDepartment().isEmpty() ||
                    employee.getPosition().isEmpty() || employee.getSalary() == null) {
                throw new RuntimeException("姓名、部门、职位、薪资不能为空！");
            }
        } catch (ParseException e) {
            request.setAttribute("errorMsg", "日期格式错误（正确：yyyy-MM-dd）");
            request.setAttribute("employee", employee);
            handleEditPage(request, response);
            return;
        } catch (Exception e) {
            request.setAttribute("errorMsg", e.getMessage());
            request.setAttribute("employee", employee);
            handleEditPage(request, response);
            return;
        }

        // 4. 更新员工
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            // 检查员工是否存在
            if (employeeMapper.selectById(id) == null) {
                request.setAttribute("errorMsg", "员工不存在");
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
                return;
            }
            // 执行更新
            int rows = employeeMapper.updateById(employee);
            if (rows > 0) {
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            } else {
                request.setAttribute("errorMsg", "更新失败");
                handleEditPage(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "更新异常：" + e.getMessage());
            handleEditPage(request, response);
        }
    }

    /**
     * 查看员工详情
     */
    private void handleView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("errorMsg", "员工ID不能为空");
            response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            return;
        }
        Integer id = Integer.parseInt(idStr);

        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.selectById(id);
            if (employee == null) {
                request.setAttribute("errorMsg", "员工不存在");
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
                return;
            }
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/employee/view.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "查看详情失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
        }
    }

    /**
     * 删除员工
     */
    private void handleDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("errorMsg", "员工ID不能为空");
            response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
            return;
        }
        Integer id = Integer.parseInt(idStr);

        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            if (employeeMapper.selectById(id) == null) {
                request.setAttribute("errorMsg", "员工不存在");
                response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
                return;
            }
            int rows = employeeMapper.deleteById(id);
            if (rows > 0) {
                request.setAttribute("successMsg", "删除成功");
            } else {
                request.setAttribute("errorMsg", "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "删除异常：" + e.getMessage());
        }

        response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
    }
}